package com.softaria.gwt.common.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Window;

public class ResizeManager {

  private final class MyWindowResizeListener implements ResizeHandler {

    public void onResize(ResizeEvent event) {
      _event = event;
      task.delay(400);
    }
  }

  private ResizeEvent _event;

  private List<ResizeHandler> listeners = new ArrayList<ResizeHandler>();

  private HandlerRegistration reg;
  private DelayedTask task = new DelayedTask(new Command() {
    public void execute() {
      fireResizeEvent();

    }
  });

  public ResizeManager() {
    // trick adopted from MyGWT Viewport. It prevents plenty of RESIZED events
    // and
    // handle it only when user stops resizing
    MyWindowResizeListener myListener = new MyWindowResizeListener();
    reg = Window.addResizeHandler(myListener);
  }

  public void addWindowResizeListener(ResizeHandler listener) {
    listeners.add(listener);
  }

  private void fireResizeEvent() {

    DeferredCommand.addCommand(new Command() {

      public void execute() {
        Iterator<ResizeHandler> it = listeners.iterator();
        while (it.hasNext()) {
          ResizeHandler listener = it.next();
          listener.onResize(_event);
        }
      }
    });

  }

  public void removeWindowResizeListener(ResizeHandler myResizeListener) {

    listeners.remove(myResizeListener);
  }

  public void dispose() {
    reg.removeHandler();
    reg = null;
    listeners.clear();

  }
}
